from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from .models import Role, UserProfile, SystemConfig, OperationLog


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'first_name', 'last_name', 'is_staff', 'is_superuser']
        read_only_fields = ['id']


class LoginSerializer(serializers.Serializer):
    """登录序列化器"""
    username = serializers.CharField(required=True)
    password = serializers.CharField(required=True, write_only=True)

    def validate(self, data):
        username = data.get('username')
        password = data.get('password')

        if username and password:
            user = authenticate(username=username, password=password)
            if user:
                if not user.is_active:
                    raise serializers.ValidationError('用户账号已被禁用')
                data['user'] = user
            else:
                raise serializers.ValidationError('用户名或密码错误')
        else:
            raise serializers.ValidationError('必须提供用户名和密码')

        return data


class RoleSerializer(serializers.ModelSerializer):
    """角色序列化器"""
    user_count = serializers.SerializerMethodField()
    
    class Meta:
        model = Role
        fields = ['id', 'name', 'description', 'permissions', 'is_active', 
                  'created_at', 'updated_at', 'user_count']
        read_only_fields = ['created_at', 'updated_at']
    
    def get_user_count(self, obj):
        return obj.userprofile_set.count()


class UserProfileSerializer(serializers.ModelSerializer):
    """用户扩展信息序列化器"""
    username = serializers.CharField(source='user.username', read_only=True)
    email = serializers.EmailField(source='user.email', read_only=True)
    role_name = serializers.CharField(source='role.name', read_only=True, allow_null=True)
    is_staff = serializers.BooleanField(source='user.is_staff', read_only=True)
    is_superuser = serializers.BooleanField(source='user.is_superuser', read_only=True)
    last_login = serializers.DateTimeField(source='user.last_login', read_only=True)
    
    class Meta:
        model = UserProfile
        fields = ['id', 'user', 'username', 'email', 'role', 'role_name',
                  'phone', 'department', 'position', 'avatar', 'last_login_ip',
                  'is_active', 'is_staff', 'is_superuser', 'last_login',
                  'created_at', 'updated_at']
        read_only_fields = ['user', 'created_at', 'updated_at']


class UserManagementSerializer(serializers.ModelSerializer):
    """用户管理序列化器（包含profile信息）"""
    profile = UserProfileSerializer(read_only=True)
    
    # 可写的profile字段
    phone = serializers.CharField(required=False, allow_blank=True, write_only=True)
    department = serializers.CharField(required=False, allow_blank=True, write_only=True)
    position = serializers.CharField(required=False, allow_blank=True, write_only=True)
    role = serializers.IntegerField(required=False, allow_null=True, write_only=True)
    password = serializers.CharField(write_only=True, required=False)
    
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'first_name', 'last_name',
                  'is_active', 'is_staff', 'is_superuser', 'date_joined',
                  'last_login', 'profile', 'phone', 'department', 'position', 'role', 'password']
        read_only_fields = ['date_joined', 'last_login']
    
    def create(self, validated_data):
        """创建用户时同时创建profile"""
        # 提取profile相关字段
        phone = validated_data.pop('phone', '')
        department = validated_data.pop('department', '')
        position = validated_data.pop('position', '')
        role_id = validated_data.pop('role', None)
        password = validated_data.pop('password', None)
        
        # 创建用户
        user = User.objects.create(**validated_data)
        
        # 设置密码
        if password:
            user.set_password(password)
            user.save()
        
        # 创建或更新profile（信号已经创建了，这里更新）
        profile = user.profile
        profile.phone = phone
        profile.department = department
        profile.position = position
        if role_id:
            profile.role_id = role_id
        profile.save()
        
        return user
    
    def update(self, instance, validated_data):
        """更新用户时同时更新profile"""
        # 记录哪些字段被提供了（用于区分"未提供"和"提供了null"）
        has_phone = 'phone' in validated_data
        has_department = 'department' in validated_data
        has_position = 'position' in validated_data
        has_role = 'role' in validated_data
        has_password = 'password' in validated_data
        
        # 提取profile相关字段
        phone = validated_data.pop('phone', None)
        department = validated_data.pop('department', None)
        position = validated_data.pop('position', None)
        role_id = validated_data.pop('role', None)
        password = validated_data.pop('password', None)
        
        # 更新用户基本信息
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        
        # 更新密码
        if has_password and password:
            instance.set_password(password)
        
        instance.save()
        
        # 更新profile（只更新提供了的字段）
        profile = instance.profile
        if has_phone:
            profile.phone = phone or ''
        if has_department:
            profile.department = department or ''
        if has_position:
            profile.position = position or ''
        if has_role:
            profile.role_id = role_id
        profile.save()
        
        return instance


class SystemConfigSerializer(serializers.ModelSerializer):
    """系统配置序列化器"""
    class Meta:
        model = SystemConfig
        fields = ['id', 'key', 'value', 'config_type', 'description',
                  'is_public', 'created_at', 'updated_at']
        read_only_fields = ['created_at', 'updated_at']


class OperationLogSerializer(serializers.ModelSerializer):
    """操作日志序列化器"""
    class Meta:
        model = OperationLog
        fields = ['id', 'user', 'username', 'log_type', 'module', 'action',
                  'ip_address', 'user_agent', 'result', 'error_message', 'created_at']
        read_only_fields = ['created_at']

